import {MangaDBTable} from "./MangaDBTable";
import {MangaSite} from "./MangaSite/MangaSite";

export namespace TableArticleList {
    export interface Data extends MangaDBTable.BaseData {
        id: number;
        article_index: number;
        book_id: number;
        download_method: MangaSite.TSiteId;
        localized: number;
        name: string;
        origin_url: string;
        img_num: number;
        read_num: number;
    }
}

export class TableArticleList extends MangaDBTable<TableArticleList.Data> {
    public static getInstance() {
        if (!TableArticleList.instance) {
            TableArticleList.instance = new TableArticleList();
        }
        return TableArticleList.instance;
    }
    private static instance: TableArticleList;
    protected defaultData: Partial<TableArticleList.Data> = {
        article_index: 0,
        origin_url: "",
        download_method: "",
        localized: 0,
    };
    constructor() {
        super("article_list");
    }
    public saveData(
        data: Partial<TableArticleList.Data>,
        mainKey: keyof TableArticleList.Data | Array<keyof TableArticleList.Data> = "id"
    ): Promise<void> {
        return super.saveData(this.mixedDefaultData(data), mainKey);
    }
    public deleteByBookIdList(bookIdList: number[]) {
        if (bookIdList.length) {
            const sql = "DELETE FROM " + this.tableName + " WHERE " + bookIdList.map((bookId) => {
                return "book_id=" + bookId;
            }).join(" OR ");
            return this.runBySql(sql);
        }
        return Promise.resolve();
    }
    public install() {
        const sql = `CREATE  TABLE  IF NOT EXISTS article_list (
           id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
           name VARCHAR(240),
           article_index INTEGER NOT NULL,
           book_id INTEGER NOT NULL,
           localized BOOLEAN NOT NULL,
           origin_url TEXT,
           download_method TEXT,
           img_num INTEGER DEFAULT 0,
           read_num INTEGER DEFAULT 0
        );`;
        return this.runBySql(sql);
    }
}
